<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>受控组件</title>
  </head>
  <body>
    <div id="test">我是一段文本</div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
      // 创建类式组件
      class Count extends React.Component {
        constructor(props) {
          console.log('constructor')
          super(props)

          // 初始化状态
          this.state = {
            count: 0
          }
        }

        addCount = () => {
          this.setState({
            count: this.state.count + 1
          })
        }

        delCom = () => {
          ReactDOM.unmountComponentAtNode(document.getElementById('test'))
        }

        // 组件将要挂载时调用
        componentWillMount() {
          console.log('componentWillMount')
        }

        // 组件挂载完毕后调用
        componentDidMount() {
          console.log('componentDidMount')
        }

        // 组件将要卸载时调用
        componentWillUnmount() {
          console.log('componentWillUnmount')
        }

        // 组件是否应该更新
        // 注意：如果写当前钩子时一定要加返回值（Boolean），false 则阻止组件更新
        shouldComponentUpdate() {
          console.log('shouldComponentUpdate')
          return true
        }

        // 组件将要更新时加载
        componentWillUpdate() {
          console.log('componentWillUpdate')
        }

        // 组件更新完毕后加载
        componentDidUpdate() {
          console.log('componentDidUpdate')
        }

        // 组价初次渲染、更新时调用
        render() {
          console.log('render')
          return (
            <div>
              <h2>当前求和：{this.state.count}</h2>
              <button onClick={this.addCount}>点我+1</button>
              <button onClick={this.delCom}>卸载</button>
            </div>
          )
        }
      }

      ReactDOM.render(<Count />, document.getElementById('test'))
    </script>
  </body>
</html>
